package com.whitedust.top30;

import com.whitedust.structure.TreeNode;

import java.util.*;

/**
 * @author A
 * @since 2025/11/3 19:14
 */

public class Top21 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        //锯齿形层序遍历，增加一个flag即可，ArrayList的reverse使用Collections
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        queue.add(root);
        int k = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode tmp = queue.poll();
                if (tmp.left != null) queue.add(tmp.left);
                if (tmp.right != null) queue.add(tmp.right);
                list.add(tmp.val);
            }
            if (k % 2 == 1) res.add(list);
            else {
                Collections.reverse(list);
                res.add(list);
            }
            k++;
        }
        return res;
    }
}
